package sf.database.template.enjoy.ext;

import com.jfinal.kit.StrKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.Template;
import com.jfinal.template.expr.ast.Const;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.jfinal.template.stat.ast.Stat;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * use指令
 */
public class UseDirective extends Directive {
    private String id;

    private static Field astField = null;

    static {
        try {
            astField = Template.class.getDeclaredField("ast");
            astField.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public void setExprList(ExprList exprList) {
        if (exprList.length() == 0) {
            throw new ParseException("The parameter of #sql directive can not be blank", location);
        }
        if (exprList.length() > 1) {
            throw new ParseException("Only one parameter allowed for #sql directive", location);
        }
        Expr expr = exprList.getExpr(0);
        if (expr instanceof Const && ((Const) expr).isStr()) {
        } else {
            throw new ParseException("The parameter of #sql directive must be String", location);
        }

        this.id = ((Const) expr).getStr();
    }

    @SuppressWarnings("unchecked")
    public void exec(Env env, Scope scope, Writer writer) {
        String nameSpace = (String) scope.get(NameSpaceDirective.NAME_SPACE_KEY);
        String key = StrKit.isBlank(nameSpace) ? id : nameSpace + "." + id;
        Map<String, Template> sqlTemplateMap = (Map<String, Template>) scope.get(SqlKit.SQL_TEMPLATE_MAP_KEY);
        if (sqlTemplateMap.containsKey(key)) {
            Template tpl = sqlTemplateMap.get(key);
            try {
                Stat stat = (Stat) astField.get(tpl);
                stat.exec(env, scope, writer);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new ParseException("Sql id not exists with key : " + key, location);
        }
    }
}
